import socket
import threading
import serial

# 初始化串口
serial_port = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)  # 修改为 Linux 的串口路径和波特率

def handle_serial_to_socket(sock):
    """从串口读取数据并发送到服务器"""
    while True:
        if serial_port.in_waiting > 0:
            serial_data = serial_port.readline().decode().strip()
            print(f"Client: {serial_data}")
            sock.sendall(serial_data.encode())

def handle_socket_to_serial(sock):
    """从服务器接收数据并发送到串口"""
    while True:
        data = sock.recv(1024)
        if not data:
            print("Connection closed by server.")
            break
        print(f"Server: {data.decode()}")
        serial_port.write(data)  # 将接收到的数据写入串口

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect(('192.168.1.113', 65432))  # 修改为服务器的实际 IP 地址
    print("Connected to the server.")

    # 创建线程分别处理串口到网络和网络到串口的通信
    serial_to_socket_thread = threading.Thread(target=handle_serial_to_socket, args=(s,))
    socket_to_serial_thread = threading.Thread(target=handle_socket_to_serial, args=(s,))
    serial_to_socket_thread.start()
    socket_to_serial_thread.start()

    # 等待线程结束
    serial_to_socket_thread.join()
    socket_to_serial_thread.join()